package net.lastcoder.ifserver.command;

import net.lastcoder.ifserver.Globals;
import net.lastcoder.ifserver.module.BaseModule;
import net.lastcoder.ifserver.module.ModuleNames;
import net.lastcoder.ifserver.util.ClassUtils;
import net.lastcoder.ifserver.util.TextUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.StringTokenizer;

/**命令管理类，处理终端的命令
 * auth: WenYF
 * date: 2016/10/26
 */
public class CommandManager extends BaseModule {
    private static final Logger Log = LoggerFactory.getLogger(CommandManager.class);

    private CommandProvider commandProvider;
    private ArrayList<CommandProcessor> processers;
    private static class SingletonHolder {
        static CommandManager instance = new CommandManager();
    }

    public static CommandManager getInstance() {
        return SingletonHolder.instance;
    }

    private CommandManager() {
        super(ModuleNames.CommandManager);
        processers = new ArrayList<>();
    }

    public void addCommandProcessor(CommandProcessor commandProcessor) {
        processers.add(commandProcessor);
    }

    public void removeCommandProcessor(CommandProcessor commandProcessor) {
        processers.remove(commandProcessor);
    }

    private void loadClass() {
        commandProvider = new DefaultCommandProvider();
    }

    @Override
    public void init() {

        loadClass();
    }

    @Override
    public void reload() {
        loadClass();
    }

    @Override
    public void destroy() {

    }

    public String processCommand(String com) {
        String ret = "";
        for (CommandProcessor processor : processers) {
            ret = processor.process(com);
            if (!TextUtils.isEmpty(ret)) {
                break;
            }
        }

        if (commandProvider != null) {
            if (TextUtils.isEmpty(ret)) {
                return commandProvider.processCommand(com);
            }
        } else {
            ret = "no command provider";
        }

        return ret;
    }

    private String next(StringTokenizer st) {
        if (st.hasMoreTokens()) {
            String str = st.nextToken();
            //System.out.println("str = " + str);
            return str;
        } else {
            return "";
        }
    }
}
